package com.monster.servlet.player;

import com.alibaba.fastjson.JSONArray;
import com.monster.pojo.Song;
import com.monster.pojo.User;
import com.monster.service.PlayerService;
import com.monster.service.PlayerServiceImpl;
import com.monster.service.SongService;
import com.monster.service.SongServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

import static javax.swing.text.html.CSS.getAttribute;

@WebServlet("/music/remove_player")
public class RemoveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PlayerService ps = new PlayerServiceImpl();
        String midArray = request.getParameter("data");
        HttpSession session = request.getSession();
        if (session.getAttribute("user") != null) {
            User user = (User) session.getAttribute("user");
            if ("all".equals(midArray)) {
                ps.deleteUserPlay(user.getId());
            } else {
                JSONArray midJSON = JSONArray.parseArray(midArray);
                for (int i = 0; i < midJSON.size(); i++) {
                    if (midJSON.getString(i) == null) {
                        continue;
                    }
                    ps.deleteUserPlay(user.getId(), Long.parseLong(midJSON.getString(i)));
                }
            }
        } else {
            if ("all".equals(midArray)) {
                session.setAttribute("playSongs", new ArrayList<Song>());
            } else if (session.getAttribute("playSongs") != null){
                ArrayList<Song> list = (ArrayList<Song>) session.getAttribute("playSongs");
                JSONArray midJSON = JSONArray.parseArray(midArray);
                SongService ss = new SongServiceImpl();
                for (int i = 0; i < midJSON.size(); i++) {
                    if (midJSON.getString(i) == null) {
                        continue;
                    }
                    list.remove(ss.getSongById(Long.parseLong(midJSON.getString(i))));
                }
                session.setAttribute("playSongs", list);
            }
        }
        request.getRequestDispatcher("list_player").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
